var pageNo = 1;
var pageSize = 10;
var queryName = "";        //商家列表查询关键字
var currentCityCode = "";  //当前城市code(用于查询列表数据)
var currentCityCodeRoot = "";  //当前城市code的最顶级编码(用于查询省市区treeSelect)
var lat;                   //纬度
var lng;                   //经度
var firstCategoryId;
var secondCategroyId;
var queryType;             //商家类型
const app = getApp();
var url = app.data.platFormUrl;
var picRoot = app.data.picRoot;
var city = require('../../utils/city.js');
var citySearch = require('../../utils/citySearchList.js');
var areaSearch = require('../../utils/areaInfo.js');
var QQMapWX = require('../../utils/qqmap-wx-jssdk.js');
var qqmapsdk;
qqmapsdk = new QQMapWX({
  //申请的腾讯地图位置服务密钥
  key: 'GSEBZ-FAFWX-PFD46-TEB2O-O2RE2-A5BGL'
});

//城市treeSelect变量
var flag = true; //表示两列
var firstCols = new Array();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    merchants:[],
    imageUrl: "" ,
    //城市下拉
    citySelected: '',
    city: '',
    currentCity:'',
    currentCityCode: '',
    currentLat:'',
    currentLng:'',
    firstCategoryId:'',
    secondCategroyId:'',
    cityData: {},
    citySearchData: {},
    citySearchKeyWord: "",
    hotCityData: [],
    provinceData: [],
    _py: ["hot", "A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "W", "X", "Y", "Z"],
    //搜索列表
    inputVal: '',
    searchList: [],
    cityListShow: false,
    inputListShow: false,
    citySearchTipListShow: false,
    hidden: true,
    showPy: '★',
    //搜索历史记录
    historyListShow: false,
    historyList: [],
    show: false,
    orderTypeShow: false,
    //省市区treeSelect
    mainActiveIndex: 0,
    activeId: null,
    showDivider: false,
    eatData:'',
    option1: [
      { text: '新兴县', value: 1 },
      { text: '郁南县', value: 2 },
      { text: '云安县', value: 3 },
      { text: '云城区', value: 4 },
      { text: '罗定市', value: 5 }
    ],
    value1: 0,
    itemTitle1: "附近",
    itemTitle2: "商圈",
    option2: [
      { text: '凤凰广场', value: 1 },
      { text: '百合山公园', value: 2 },
      { text: '时代广场', value: 3 },
    ],
    value2: 1,
    items:[
      
    ],
    serviceArr:[],
    address:'',
    phone:'',
    longitude:'',
    latitude:'',
    merchantName:'',
    scrollHeight: 0
  },
  closeOrderTypePup: function(){
    let _that = this;
    _that.setData({
      orderTypeShow: false
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log(options);
    //变量赋值
    currentCityCode = options.cityCode;
    lat = options.lat;
    lng = options.lng;
    queryType = options.type;
    firstCategoryId = options.firstId;
    secondCategroyId = options.secondId;
    //页面数据赋值
    var th = this;
    th.setData({
      cityData: city.all,
      hotCityData: city.hot,
      provinceData: city.province,
      citySearchData: citySearch.data,
      citySelected: options.city,
      city: options.city,
      currentCity: options.city,
      currentCityCode: options.cityCode,
      currentLat: options.lat,
      currentLng: options.lng,
      firstCategoryId: options.firstCategoryId,
      secondCategroyId: options.secondCategroyId
    });

    //根据获取的当前城市,填充'附近'下拉市区数据
    var areaData = areaSearch.data;
    //console.log("附近下拉" + JSON.stringify(areaData));
    outer:
    for (var i = 0; i < areaData.all.length; i++) {
      //循环省
      var citys = areaData.all[i].children;
      for(var k = 0; k < citys.length; k++){
        //循环市
        if (currentCityCode == citys[k].id){
          //console.log("匹配城市:" + JSON.stringify(citys));
          th.setData({
            items: citys[k].children
          })
          break outer;
        }
      }
    }
  
    
    //调用获取城市列表接口
    /*qqmapsdk.getCityList({
      success: function (res) {//成功后的回调
        console.log(res);
        console.log('城市数据：', JSON.stringify(res.result[2])); //打印城市数据
      },
      fail: function (error) {
        console.error(error);
      },
      complete: function (res) {
        console.log(res);
      }
    });*/

    //th.fillCityTreeSelect();

    //初始化搜索列表
    th.queryTable(pageNo, pageSize, queryName, queryType, currentCityCode, lat, lng, false, "", firstCategoryId, secondCategroyId);

    //获取手机可视高度，设置商家菜单高度，塞满
    wx.getSystemInfo({
      
      success: function (res) {
        // 获取可使用窗口宽度
        let clientHeight = res.windowHeight;
        // 获取可使用窗口高度
        let clientWidth = res.windowWidth;
        // 算出比例
        let ratio = 750 / clientWidth;
        //手机型号
        let mobileModel = res.model;
        // 算出高度(单位rpx)
        let height = clientHeight * ratio;
        console.info("---------------------------------" + height + "--------------------------")
        //高度减去顶部和底部
        height = height - 54;
        if (mobileModel.indexOf("iPhone XR") != -1
          || mobileModel.indexOf("iPhone XS") != -1
          || mobileModel.indexOf("iPhone 11") != -1) {
          height = height - 50;
        }
        console.info("---------------------------------" + height + "--------------------------")
        console.info("-------------------" + mobileModel + "---------------");
        //设置高度
        th.setData({
          scrollHeight: height
        })
      }
    });
    
  },
  makeCall: function () {
    console.log("打电话");
    wx.makePhoneCall({
      phoneNumber: this.data.phone,
      success: function () {
        console.log("成功拨打电话")
      },
      fail: function () {
        console.log("拨打电话失败！")
      }
    })

  },
  location: function () {
    var that = this;
    var name = this.data.merchantName;
    var addr = this.data.address;
    //使用后台维护的腾讯服务经纬度(火星坐标系)
    wx.openLocation({
      longitude: Number(this.data.longitude),
      latitude: Number(this.data.latitude),
      name: name,
      address: addr
    })
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    //页面渲染完成
  },

  /**选择服务类型 */
  chooseService: function(event){
    console.log(event);
    let data = JSON.stringify(event.currentTarget.dataset)
    console.info(data);
    let _that = this;
    _that.setData({
      address: event.currentTarget.dataset.addr,
      phone: event.currentTarget.dataset.phone,
      longitude: event.currentTarget.dataset.lot,
      latitude: event.currentTarget.dataset.lat,
      merchantName: event.currentTarget.dataset.name
    })
    // 查询服务类型
    wx.request({
      url: url + '/ItemApi/queryEatServiceById',
      data: {
        merchantId: event.currentTarget.dataset.id,
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        if (res.data.code == 200) {
          _that.setData({
            serviceArr: res.data.data
          })
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: "none",
            duration: 2000
          })
        }
      },
      fail: function (res) {
        console.info('submit fail');
      },
      complete: function (res) {
        console.info('submit complete');
      }
    })

    _that.setData({ 
      orderTypeShow: true,
      eatData: data
    });
  },
  /**游览商品 */
  visitShopDetail: function(e){
    let _that = this;
     // 餐饮
     let eatData = _that.data.eatData;
     var orderType = "-1";
     let urls = '../../pages/detail/index?data=' + eatData + "&queryType=" + queryType + "&orderType=" + orderType;
     wx.navigateTo({
      url: urls
    })
  },
  /**
   * 跳转店铺详情
   */
  toShopDetail: function(e){
    let _that = this;
    var tempData = JSON.stringify(e.currentTarget.dataset);
    // 0餐饮 1非餐饮
    var type = e.currentTarget.dataset.type;
    var urls = "";
    if (type == "0"){
        // 餐饮
      let eatData = tempData;
      //let eatData = _that.data.eatData;
      //var orderType = e.currentTarget.dataset.ordertype;
      //var sendPrice = e.currentTarget.dataset.item.sendPrice;
      urls = '../../pages/detail/index?data=' + eatData
      //urls = '../../pages/detail/index?data=' + eatData + "&queryType=" + queryType + "&orderType=" + orderType + "&sendPrice=" + sendPrice
    } else {
      // 非餐饮
      urls = '../../pages/merchant/index?data=' + tempData + "&merchantId=" + e.currentTarget.dataset.id
    }
    console.log(urls);
    wx.navigateTo({
      url: urls
    })
  },

  /**
   * 上拉触底加载更多数据
   */
  onReachBottom: function () {
    pageNo = pageNo + 1;
    console.info(pageNo);
    var th = this;
    th.queryTable(pageNo, pageSize, queryName, queryType, currentCityCode, lat, lng, true, "", firstCategoryId, secondCategroyId);
  },

  /**
   * 监听用户下拉动作(下拉刷新)
   */
  onPullDownRefresh: function () {
    //显示顶部刷新图标
    wx.showNavigationBarLoading();
    var th = this;
    wx.getLocation({
      type: "gcj02",
      success: function (res) {
        pageNo = 1;
        lat = res.latitude;
        lng = res.longitude;
        wx.request({
          url: url + '/MerchantApi/listPageMerchant',
          data: { pageNo: pageNo, pageSize: pageSize, name: queryName, type: queryType, lat: lat, lng: lng, cityCode: currentCityCode },
          method: 'POST',
          header: { 'content-type': 'application/x-www-form-urlencoded' },
          success: function (res) {
            console.info(res.data);
            if (res.data.code == 200) {
              for (var i = 0; i < res.data.data.pageList.length; i++) {
                res.data.data.pageList[i].coverIcon = picRoot + res.data.data.pageList[i].coverIcon
              }
              th.setData({
                merchants: res.data.data.pageList
              })
              wx.hideNavigationBarLoading() //完成停止加载
              wx.stopPullDownRefresh() //停止下拉刷新
            } else {
              wx.showToast({
                title: res.data.msg,
                icon: "loading",
                duration: 2000
              })
            }

          },
          fail: function (res) {
            console.info('submit fail');
          },
          complete: function (res) {
            console.info('submit complete');
          }

        })
      },
      fail: function (res) {

      }
    })
    
  },

  getLoc: function(){
    wx.getLocation({
      type: 'gcj02', // 返回可以用于wx.openLocation的经纬度
      success(res) {
        console.info(res);
        const latitude = res.latitude
        const longitude = res.longitude
        wx.openLocation({
          latitude,
          longitude,
          scale: 18
        })
      }
    })
  },

  onSearch: function(e){
    var th = this;
    pageNo = 1;
    pageSize = 10;
    queryName = e.detail;
    console.info(e.detail);
    th.queryTable(pageNo, pageSize, queryName, queryType, currentCityCode, lat, lng, false, "", firstCategoryId, secondCategroyId);
  },
  
  //打开城市列表
    openCityList: function () {
      var th = this;
      th.setData({
        cityListShow: true,
        inputListShow: false,
        historyListShow: false,
        show: true
      });
    },

  //选择城市
  selectCity: function (e) {
    var th = this;
    var dataset = e.currentTarget.dataset;
    th.setData({
      citySelected: dataset.fullname,
      city: dataset.fullname,
      cityListShow: false,
      inputListShow: false,
      historyListShow: true,
      location: {
        latitude: dataset.lat,
        longitude: dataset.lng
      },
      show: false
    });
    //按选中城市或者区县刷新列表
    console.log("选择城市/县区 code:" + dataset.code);
    currentCityCode = dataset.code;
    currentCityCodeRoot = dataset.root;
    pageNo = 1;
    th.queryTable(pageNo, pageSize, queryName, queryType, dataset.code, lat, lng, false, "", firstCategoryId, secondCategroyId);
    //填充省市区treeSelect
    /*var areaData = areaSearch.data;
    console.log(areaData);
    for(var i = 0; i < areaData.all.length; i++){
      if (areaData.all[i].id == currentCityCodeRoot){
        console.log("选中城市:" + JSON.stringify(areaData));
        th.setData({
          items: areaData.all[i].children
        })
      }
    }*/
    var areaData = areaSearch.data
    outer:
    for (var i = 0; i < areaData.all.length; i++) {
      //循环省
      var citys = areaData.all[i].children;
      for (var k = 0; k < citys.length; k++) {
        //循环市
        if (currentCityCode == citys[k].id) {
          //console.log("匹配城市:" + JSON.stringify(citys));
          th.setData({
            items: citys[k].children
          })
          break outer;
        }
      }
    }

  },
  touchstart: function (e) {
    this.setData({
      index: e.currentTarget.dataset.index,
      Mstart: e.changedTouches[0].pageX
    });
  },
  touchmove: function (e) {
    var history = this.data.historyList;
    var move = this.data.Mstart - e.changedTouches[0].pageX;
    history[this.data.index].x = move > 0 ? -move : 0;
    this.setData({
      historyList: history
    });
  },
  touchend: function (e) {
    var history = this.data.historyList;
    var move = this.data.Mstart - e.changedTouches[0].pageX;
    history[this.data.index].x = move > 100 ? -180 : 0;
    this.setData({
      historyList: history
    });
  },
  //获取文字信息
  getPy: function (e) {
    this.setData({
      hidden: false,
      showPy: e.target.id,
    })
    console.info("*****************" + e.target.id);
  },

  setPy: function (e) {
    this.setData({
      hidden: true,
      scrollTopId: this.data.showPy
    })
    console.log("-----------------" + this.data.showPy + "-----------------");
  },

  //滑动选择城市
  tMove: function (e) {
    var y = e.touches[0].clientY,
      offsettop = e.currentTarget.offsetTop;

    //判断选择区域,只有在选择区才会生效
    if (y > offsettop) {
      var num = parseInt((y - offsettop) / 12);
      this.setData({
        showPy: this.data._py[num]
      })
    };
  },

  //触发全部开始选择
  tStart: function () {
    this.setData({
      hidden: false
    })
  },

  //触发结束选择
  tEnd: function () {
    this.setData({
      hidden: true,
      scrollTopId: this.data.showPy
    })
  },

  onClose() {
    this.setData({ show: false });
  },

  citySearchOnFocus(e) {
    this.setData({
      cityListShow: false,
      citySearchTipListShow: true
    });
  },

  citySearchOnBlur(e) {
    this.setData({
      cityListShow: true,
    });
  },

  citySearchOnChange(e) {

    this.setData({
      citySearchKeyWord: e.detail,
    });
  },

  onClickNav({ detail = {} }){
    var th = this;
    th.setData({
      mainActiveIndex: detail.index || 0
    });
    console.info("***************" + JSON.stringify(th.data.items));
  },

  onClickItem(event) {
    var th = this;
    console.log("点击右侧: " + JSON.stringify(event));
    console.log("根据townCode: " + event.detail.id + "(" + event.detail.text + ")" +  "-----查询列表数据");
    th.selectComponent('#item').toggle();
    if (event.detail.text != "全部"){
      th.setData({
        itemTitle1: event.detail.text
      })
    } else {
      th.setData({
        itemTitle1: "附近"
      })
    }
    th.queryTable(1, 10, queryName, queryType, "", lat, lng, false, event.detail.id, firstCategoryId, secondCategroyId);

  },

  fillCityTreeSelect(){
    var id = "";
    var array;
    var th = this;
    qqmapsdk.getDistrictByCityId({
      // 传入对应省份ID获得城市数据，传入城市ID获得区县数据,依次类推
      id: "445300", //对应接口getCityList返回数据的Id，如：北京是'110000'
      success: function (res) {//成功后的回调
        console.log('对应城市ID下的区县数据', JSON.stringify(res.result[0]));
        array = new Array();
        for (var i = 0; i < res.result[0].length; i++) {
          var o = new Object();
          o.id = res.result[0][i].id;
          o.text = res.result[0][i].fullname;
          array[i] = o;
        }
        if (res.result[0].length > 0 && res.result[0][0].id.length <= 6){
          id = res.result[0][0].id;
        }
        //塞进TreeSelect控件
        th.setData({
          items: array
        })
      },
      fail: function (error) {
        console.error(error);
      },
      complete: function (res) {
        if (id != ""){
          qqmapsdk.getDistrictByCityId({
            // 传入对应省份ID获得城市数据，传入城市ID获得区县数据,依次类推
            id: id, //对应接口getCityList返回数据的Id，如：北京是'110000'
            success: function (res) {//成功后的回调
              console.log('对应城市ID下的区县数据', res.result[0]);
              var array2 = new Array();
              for (var i = 0; i < res.result[0].length; i++) {
                var o2 = new Object();
                o2.id = res.result[0][i].id;
                o2.text = res.result[0][i].fullname;
                array2[i] = o2;
              }
              if (array2.length > 0 && array2[0].id.length <= 6) {
                array[0].children = array2;
                //塞进TreeSelect控件
                th.setData({
                  items: array
                })
              }
              
            }
          });
        }
        
      }
    });
  },

  //列表搜索通用函数
  queryTable(pageNo,pageSize,queryName,queryType,cityCode,lat,lng,flag,town, firstCategoryId, secondCategoryId) {
    var th = this;
        wx.request({
          url: url + '/MerchantApi/client/noAuth/listPageMerchantForIndex',
          data: { firstCategoryId: firstCategoryId, secondCategoryId: secondCategoryId, pageNo: pageNo, pageSize: pageSize, name: queryName, type: queryType, latitude: lat, longitude: lng, cityCode: cityCode, town: town },
          method: 'POST',
          header: { 'content-type': 'application/json' },
          success: function (res) {
            console.info(res.data);
            if (res.data.code == 200) {
              for (var i = 0; i < res.data.data.pageList.length; i++){
                res.data.data.pageList[i].coverIcon = picRoot + res.data.data.pageList[i].coverIcon
              }
              if(!flag){
                console.log(res.data.data.pageList);
                th.setData({
                  merchants: res.data.data.pageList
                })
              } else {
                if (res.data.data.pageList.length > 0) {
                  th.setData({
                    merchants: th.data.merchants.concat(res.data.data.pageList)
                  })
                } else {
                  /*wx.showToast({
                    title: '没有数据啦',
                    icon: "loading",
                    duration: 2000
                  })*/
                  th.setData({
                    showDivider: true
                  })
                }
              }
            } else {
              wx.showToast({
                title: res.data.msg,
                icon: "loading",
                duration: 2000
              })
            }
          },
          fail: function (res) {
            console.info('submit fail');
          },
          complete: function (res) {
            console.info('submit complete');
          }
        })
  }
  


})